<template>
	<div class="wrapper">

		<!-- header部分 -->
		<header>
			<p ref="fixedBox" class="fixed-top"><Back></Back>我的钱包</p>
		</header>

		<!-- 钱包信息部分 -->
		<div class="wallet-info">
			<div v-if="walletInfo">
				<div class="balance-card">
					<div class="balance-title">我的余额</div>
					<div class="balance-amount">¥{{ walletInfo.balance }}</div>
					<div class="balance-buttons">
						<button @click="showRechargeDialog" class="btn-recharge">充值</button>
						<button @click="showWithdrawDialog" class="btn-withdraw">提现</button>
					</div>
				</div>
				
				<div v-if="walletInfo.vipFlag" class="vip-info">
					<div class="vip-title">
						<i class="fa fa-diamond"></i> VIP会员
					</div>
					<div class="vip-detail">额度上限: ¥{{ walletInfo.maxOverdraft }}</div>
				</div>
				<div v-else class="vip-upgrade">
					<button @click="showVipDialog" class="btn-vip">开通VIP</button>
					<p>开通VIP享受更多特权</p>
				</div>
			</div>
			<div v-else class="wallet-create">
				<p>您还没有创建钱包</p>
				<button @click="showCreateWalletDialog" class="btn-create">创建钱包</button>
			</div>
		</div>

		<!-- 交易记录部分 -->
		<div class="transaction-section" v-if="walletInfo">
			<div class="transaction-header">
				<div class="transaction-title">交易记录</div>
				<div class="transaction-tabs">
					<span 
						:class="{ active: activeTab === 'all' }" 
						@click="switchTab('all')">全部</span>
					<span 
						:class="{ active: activeTab === 'income' }" 
						@click="switchTab('income')">收入</span>
					<span 
						:class="{ active: activeTab === 'expense' }" 
						@click="switchTab('expense')">支出</span>
				</div>
			</div>
			
			<ul class="transaction-list">
				<li v-for="(item, index) in filteredTransactions" :key="index" class="transaction-item" @click="viewTransactionDetail(item)">
					<div class="transaction-info">
						<div class="transaction-date">{{ formatTime(item.transactionTime) }}</div>
						<div class="transaction-desc">
							{{ getTransactionDesc(item) }}
						</div>
					</div>
					<div :class="['transaction-amount', isIncome(item) ? 'income' : 'expense']">
						¥{{ getTransactionAmount(item) }}
					</div>
				</li>
				<li v-if="filteredTransactions.length === 0" class="no-transactions">
					暂无交易记录
				</li>
			</ul>
		</div>

		<!-- 创建钱包弹窗 -->
		<div class="dialog-overlay" v-if="showCreateWallet">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>创建钱包</h3>
					<span @click="showCreateWallet = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<div class="form-item">
						<label>设置支付密码</label>
						<input type="password" v-model="walletPassword" placeholder="请输入6位数字密码" maxlength="6">
					</div>
					<div class="form-item">
						<label>确认支付密码</label>
						<input type="password" v-model="confirmWalletPassword" placeholder="请再次输入密码" maxlength="6">
					</div>
				</div>
				<div class="dialog-footer">
					<button @click="createWallet" class="dialog-btn">确认创建</button>
				</div>
			</div>
		</div>

		<!-- 充值弹窗 -->
		<div class="dialog-overlay" v-if="showRecharge">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>钱包充值</h3>
					<span @click="showRecharge = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<div class="form-item">
						<label>充值金额</label>
						<input type="number" v-model="rechargeAmount" placeholder="请输入充值金额">
					</div>
					<div class="form-item">
						<label>支付密码</label>
						<input type="password" v-model="payPassword" placeholder="请输入支付密码" maxlength="6">
					</div>
				</div>
				<div class="dialog-footer">
					<button @click="rechargeWallet" class="dialog-btn">确认充值</button>
				</div>
			</div>
		</div>

		<!-- 提现弹窗 -->
		<div class="dialog-overlay" v-if="showWithdraw">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>钱包提现</h3>
					<span @click="showWithdraw = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<div class="form-item">
						<label>提现金额</label>
						<input type="number" v-model="withdrawAmount" placeholder="请输入提现金额">
					</div>
					<div class="form-item">
						<label>支付密码</label>
						<input type="password" v-model="payPassword" placeholder="请输入支付密码" maxlength="6">
					</div>
				</div>
				<div class="dialog-footer">
					<button @click="withdrawWallet" class="dialog-btn">确认提现</button>
				</div>
			</div>
		</div>

		<!-- VIP弹窗 -->
		<div class="dialog-overlay" v-if="showVip">
			<div class="dialog-container">
				<div class="dialog-header">
					<h3>开通VIP</h3>
					<span @click="showVip = false" class="dialog-close">&times;</span>
				</div>
				<div class="dialog-content">
					<div class="vip-benefits">
						<p><i class="fa fa-check"></i> 更高的欠款额度</p>
						<p><i class="fa fa-check"></i> 专属客服支持</p>
						<p><i class="fa fa-check"></i> 交易手续费减免</p>
					</div>
					<div class="form-item">
						<label>支付密码</label>
						<input type="password" v-model="payPassword" placeholder="请输入支付密码" maxlength="6">
					</div>
				</div>
				<div class="dialog-footer">
					<button @click="upgradeToVip" class="dialog-btn">确认开通</button>
				</div>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
	import Footer from '../components/Footer.vue';
	import Back from '../components/Back.vue';
	
	export default{
		name: 'MyWallet',
		components: {
			Footer,
			Back
		},
		data() {
			return {
				user: null,
				walletInfo: null,
				walletId: null,
				transactions: [],
				
				// 标签页
				activeTab: 'all',
				
				// 创建钱包
				showCreateWallet: false,
				walletPassword: '',
				confirmWalletPassword: '',
				
				// 充值
				showRecharge: false,
				rechargeAmount: null,
				
				// 提现
				showWithdraw: false,
				withdrawAmount: null,
				
				// VIP
				showVip: false,
				
				// 支付密码
				payPassword: ''
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');
			if (this.user) {
				this.checkWallet();
			}
		},
		computed: {
			filteredTransactions() {
				if (this.activeTab === 'all') {
					return this.transactions;
				} else if (this.activeTab === 'income') {
					return this.transactions.filter(item => item.toWalletId === this.walletId);
				} else if (this.activeTab === 'expense') {
					return this.transactions.filter(item => item.fromWalletId === this.walletId);
				}
				return this.transactions;
			}
		},
		methods: {
			// 检查钱包
			checkWallet() {
				// 这里假设钱包ID和用户ID一致，如果后端不一致需要调整
				this.walletId = this.user.userId;
				
				// 尝试获取钱包信息
				this.$axios.get(`WalletController/getWallet/${this.walletId}`)
					.then(response => {
						if (response.data.code === 200 && response.data.result) {
							this.walletInfo = response.data.result;
							// 获取余额
							this.getBalance();
							// 获取交易记录
							this.getTransactions();
						}
					})
					.catch(error => {
						console.error('获取钱包信息失败', error);
						this.walletInfo = null;
					});
			},
			
			// 获取余额
			getBalance() {
				this.$axios.get(`WalletController/getBalance/${this.walletId}`)
					.then(response => {
						if (response.data.code === 200) {
							this.walletInfo.balance = response.data.result;
						}
					})
					.catch(error => {
						console.error('获取余额失败', error);
					});
			},
			
			// 获取交易记录
			getTransactions() {
				this.$axios.get(`WalletController/listTransactionByWalletId/${this.walletId}`)
					.then(response => {
						if (response.data.code === 200) {
							this.transactions = response.data.result || [];
							console.log('交易记录数据:', this.transactions);
						}
					})
					.catch(error => {
						console.error('获取交易记录失败', error);
					});
			},
			
			// 切换交易记录标签
			switchTab(tab) {
				this.activeTab = tab;
			},
			
			// 创建钱包对话框
			showCreateWalletDialog() {
				this.showCreateWallet = true;
				this.walletPassword = '';
				this.confirmWalletPassword = '';
			},
			
			// 创建钱包
			createWallet() {
				if (!this.walletPassword) {
					alert('请输入支付密码');
					return;
				}
				
				if (this.walletPassword !== this.confirmWalletPassword) {
					alert('两次输入密码不一致');
					return;
				}
				
				if (!/^\d{6}$/.test(this.walletPassword)) {
					alert('请输入6位数字密码');
					return;
				}
				
				this.$axios.post(`WalletController/createWallet/${this.user.userId}/${this.walletPassword}`)
					.then(response => {
						if (response.data.code === 200) {
							alert('钱包创建成功');
							this.showCreateWallet = false;
							this.checkWallet();
						} else {
							alert('钱包创建失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('创建钱包失败', error);
						alert('创建钱包失败，请稍后重试');
					});
			},
			
			// 充值对话框
			showRechargeDialog() {
				this.showRecharge = true;
				this.rechargeAmount = null;
				this.payPassword = '';
			},
			
			// 充值
			rechargeWallet() {
				if (!this.rechargeAmount || this.rechargeAmount <= 0) {
					alert('请输入有效的充值金额');
					return;
				}
				
				if (!this.payPassword) {
					alert('请输入支付密码');
					return;
				}
				
				this.$axios.post(`WalletController/recharge/${this.walletId}/${this.rechargeAmount}/${this.payPassword}`)
					.then(response => {
						if (response.data.code === 200) {
							alert('充值成功');
							this.showRecharge = false;
							this.getBalance();
							this.getTransactions();
						} else {
							alert('充值失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('充值失败', error);
						alert('充值失败，请检查支付密码或稍后重试');
					});
			},
			
			// 提现对话框
			showWithdrawDialog() {
				this.showWithdraw = true;
				this.withdrawAmount = null;
				this.payPassword = '';
			},
			
			// 提现
			withdrawWallet() {
				if (!this.withdrawAmount || this.withdrawAmount <= 0) {
					alert('请输入有效的提现金额');
					return;
				}
				
				if (!this.payPassword) {
					alert('请输入支付密码');
					return;
				}
				
				this.$axios.post(`WalletController/withdraw/${this.walletId}/${this.withdrawAmount}/${this.payPassword}`)
					.then(response => {
						if (response.data.code === 200) {
							alert('提现成功');
							this.showWithdraw = false;
							this.getBalance();
							this.getTransactions();
						} else {
							alert('提现失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('提现失败', error);
						alert('提现失败，请检查余额和支付密码');
					});
			},
			
			// VIP对话框
			showVipDialog() {
				this.showVip = true;
				this.payPassword = '';
			},
			
			// 开通VIP
			upgradeToVip() {
				if (!this.payPassword) {
					alert('请输入支付密码');
					return;
				}
				
				this.$axios.post(`WalletController/getVip/${this.walletId}/${this.payPassword}`)
					.then(response => {
						if (response.data.code === 200) {
							alert('VIP开通成功');
							this.showVip = false;
							this.checkWallet();
						} else {
							alert('VIP开通失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('VIP开通失败', error);
						alert('VIP开通失败，请检查支付密码');
					});
			},
			
			// 格式化交易时间
			formatTime(time) {
				if (!time) return '';
				const date = new Date(time);
				return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`;
			},
			
			padZero(num) {
				return num < 10 ? `0${num}` : num;
			},
			
			// 判断是否为收入
			isIncome(item) {
				return item.toWalletId === this.walletId;
			},
			
			// 获取交易金额
			getTransactionAmount(item) {
				return item.transactionAmount || 0;
			},
			
			// 获取交易描述
			getTransactionDesc(item) {
				// 根据fromWalletId和toWalletId判断交易类型
				// 如果没有from，只有to，说明是充值
				if (!item.fromWalletId && item.toWalletId) {
					return '钱包充值';
				}
				// 如果有from，没有to，说明是提现
				else if (item.fromWalletId && !item.toWalletId) {
					return '钱包提现';
				}
				// 如果是自己付款
				else if (item.fromWalletId == this.walletId) {
					return '支付';
				}
				// 如果是收款
				else if (item.toWalletId == this.walletId) {
					return '收款';
				}
				else {
					return '交易';
				}
			},
			
			// 点击交易记录跳转到详情页面
			viewTransactionDetail(item) {
				this.$router.push({
					path: '/transactionDetail',
					query: {
						transactionId: item.transferId
					}
				});
			}
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}
	.wrapper header .fixed-top {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;
		
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
		
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.wrapper header Back {
		margin-left: 2.5vw;
	}

	/****************** 钱包信息部分 ******************/
	.wallet-info {
		margin-top: 16vw;
		padding: 4vw;
	}

	.wallet-create {
		background-color: #fff;
		border-radius: 8px;
		padding: 5vw;
		text-align: center;
		box-shadow: 0 2px 5px rgba(0,0,0,0.1);
	}

	.wallet-create p {
		margin-bottom: 3vw;
		font-size: 4.5vw;
		color: #333;
	}

	.btn-create {
		background-color: #0097FF;
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 2.5vw 5vw;
		font-size: 4vw;
	}

	.balance-card {
		background-color: #0097FF;
		border-radius: 8px;
		padding: 5vw;
		color: #fff;
		box-shadow: 0 2px 5px rgba(0,0,0,0.1);
	}

	.balance-title {
		font-size: 4vw;
		margin-bottom: 2vw;
	}

	.balance-amount {
		font-size: 8vw;
		font-weight: bold;
		margin-bottom: 4vw;
	}

	.balance-buttons {
		display: flex;
		justify-content: space-between;
	}

	.btn-recharge, .btn-withdraw {
		background-color: rgba(255,255,255,0.2);
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 2vw 4vw;
		font-size: 3.5vw;
		width: 48%;
	}

	.vip-info, .vip-upgrade {
		background-color: #fff;
		border-radius: 8px;
		padding: 4vw;
		margin-top: 3vw;
		box-shadow: 0 2px 5px rgba(0,0,0,0.1);
	}

	.vip-title {
		color: #FFB800;
		font-size: 4.5vw;
		font-weight: bold;
		margin-bottom: 2vw;
	}

	.vip-detail {
		color: #666;
		font-size: 3.5vw;
	}

	.vip-upgrade {
		text-align: center;
	}

	.vip-upgrade p {
		color: #666;
		font-size: 3.5vw;
		margin-top: 2vw;
	}

	.btn-vip {
		background-color: #FFB800;
		color: #fff;
		border: none;
		border-radius: 4px;
		padding: 2vw 4vw;
		font-size: 3.5vw;
	}

	/****************** 交易记录部分 ******************/
	.transaction-section {
		margin-top: 3vw;
		padding: 0 4vw 20vw 4vw;
	}

	.transaction-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 3vw;
	}

	.transaction-title {
		font-size: 4.5vw;
		font-weight: bold;
		color: #333;
	}

	.transaction-tabs {
		display: flex;
	}

	.transaction-tabs span {
		margin-left: 2vw;
		font-size: 3.5vw;
		color: #666;
		padding-bottom: 1vw;
		position: relative;
	}

	.transaction-tabs span.active {
		color: #0097FF;
	}

	.transaction-tabs span.active:after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 0.5vw;
		background-color: #0097FF;
	}

	.transaction-list {
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.transaction-item {
		display: flex;
		justify-content: space-between;
		padding: 3vw 4vw;
		border-bottom: 1px solid #f0f0f0;
	}

	.transaction-info {
		flex: 1;
	}

	.transaction-date {
		font-size: 3vw;
		color: #999;
		margin-bottom: 1vw;
	}

	.transaction-desc {
		font-size: 3.8vw;
		color: #333;
	}

	.transaction-amount {
		font-size: 4vw;
		font-weight: bold;
	}

	.transaction-amount.income {
		color: #38CA73;
	}

	.transaction-amount.expense {
		color: #FF5252;
	}

	.no-transactions {
		padding: 5vw;
		text-align: center;
		color: #999;
		font-size: 3.8vw;
	}

	/****************** 弹窗样式 ******************/
	.dialog-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0,0,0,0.5);
		z-index: 2000;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dialog-container {
		width: 80%;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.dialog-header {
		padding: 3vw 4vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f0f0;
	}

	.dialog-header h3 {
		font-size: 4.5vw;
		color: #333;
		margin: 0;
	}

	.dialog-close {
		font-size: 6vw;
		color: #999;
		cursor: pointer;
	}

	.dialog-content {
		padding: 4vw;
	}

	.form-item {
		margin-bottom: 3vw;
	}

	.form-item label {
		display: block;
		margin-bottom: 2vw;
		font-size: 3.8vw;
		color: #333;
	}

	.form-item input {
		width: 100%;
		padding: 2.5vw;
		border: 1px solid #ddd;
		border-radius: 4px;
		font-size: 3.8vw;
		box-sizing: border-box;
	}

	.dialog-footer {
		padding: 3vw 4vw;
		border-top: 1px solid #f0f0f0;
	}

	.dialog-btn {
		width: 100%;
		padding: 2.5vw;
		background-color: #0097FF;
		color: #fff;
		border: none;
		border-radius: 4px;
		font-size: 4vw;
	}

	.vip-benefits {
		background-color: #f9f9f9;
		padding: 3vw;
		border-radius: 4px;
		margin-bottom: 3vw;
	}

	.vip-benefits p {
		margin: 2vw 0;
		font-size: 3.5vw;
		color: #666;
	}

	.vip-benefits i {
		color: #FFB800;
		margin-right: 1vw;
	}
</style>
